# -*- coding: utf-8 -*-
import datetime
import os
import re
import sys
import urllib2

from codes import *
from errors import CurrencyConvertError
from db import CurrenciesDb
import banks
import conf

def equals(a, b):
    "Compare two float or ints by 2 digits"
    return round(a - b, 2) == 0

cdb = None
def convert(value, source_currency, target_currency, date=None):
    """
    Convert money value from source_currency to target_currency
    """
    if value == 0:
        return float(value)

    global cdb

    if cdb is None:  # lazy connection
        if sys.platform == 'win32' or not os.path.exists('/var/currencies/'):
            dbpath = os.path.join(os.path.dirname(__file__), 'currencies.sqlite')
        else:
            dbpath = '/var/currencies/db.sqlite'
        cdb = CurrenciesDb(dbpath)

    if date is None:
        date = datetime.date.today()

#    if date.year <= conf.FIRST_DENOMINATION_YEAR:
#        if source_currency == RUB:


    try:
        rate = specialcase_rate(source_currency, target_currency, date) or \
               cdb.get_rate(source_currency, target_currency, date, banks.CBR_RU)
    except urllib2.HTTPError:
        raise CurrencyConvertError('Cannot connect to currency rates server. Try again.')

    if rate is None:
        raise CurrencyConvertError('Cannot get rate for source_currency %d, '
            'target_currency %d, date %s' % (source_currency, target_currency, date))

    return float(value) * rate


def specialcase_rate(source_currency, target_currency, date):
    if source_currency == target_currency:
        return 1

    if source_currency == RUR and target_currency == RUB:
        return 0.001

    if source_currency == RUB and target_currency == RUR:
        return 1000.0

    return None
